package com.m3958.encode.detector.impl;

import java.nio.file.Path;

import com.m3958.encode.detector.AbstractDetector;
import com.m3958.encode.detector.Detector;
import com.m3958.encode.detector.LanguageName;

public class Gb2312 extends AbstractDetector implements Detector {

    public Gb2312() {
    }

    public Gb2312(byte[] bytes) {
        super(bytes);
    }

    public Gb2312(Path path) {
        super(path);
    }

    public static final byte GB2312_FRONT_BOTTOM = (byte) 0xA1; // -95
    public static final byte GB2312_FRONT_TOP = (byte) 0xF7; // -9

    public static final byte GB2312_REAR_BOTTOM = (byte) 0xA1; // -95
    public static final byte GB2312_REAR_TOP = (byte) 0xFE; // -2

    public static final byte GB2312_CHINESE_FRONT_BOTTOM = (byte) 0xB0; // -80
    public static final byte GB2312_CHINESE_FRONT_TOP = (byte) 0xFE; // -2

    public static final byte GB2312_OTHERS_FRONT_BOTTOM = (byte) 0xA1; // -95
    public static final byte GB2312_OTHERS_FRONT_TOP = (byte) 0xA9; // -87

    protected boolean isGb2312FirstByte(byte b) {
        if (b == GB2312_CHINESE_FRONT_BOTTOM || b == GB2312_CHINESE_FRONT_TOP) {
            return true;
        }
        return b > GB2312_CHINESE_FRONT_BOTTOM && b < GB2312_CHINESE_FRONT_TOP;
    }

    protected boolean isGb2312SecondByte(byte b) {
        if (b == GB2312_REAR_BOTTOM || b == GB2312_REAR_TOP) {
            return true;
        }
        return b > GB2312_REAR_BOTTOM && b < GB2312_REAR_TOP;
    }

    @Override
    public int maxCharBytes() {
        return 2;
    }

    @Override
    protected int detectOne(byte... bytes) {
        int len = bytes.length;

        switch (len) {
        case 1:
            if (isAscii(bytes[0])) {
                successedNumber++;
                asciiNumber++;
                return 0;
            } else {
                return 1;
            }
        case 2:
            if (isGb2312FirstByte(bytes[0]) && isGb2312SecondByte(bytes[1])) {
                successedNumber++;
                charNumber++;
            } else if (isAscii(bytes[1])) {
                asciiNumber++;
                failedNumber++;
            } else {
                failedNumber++;
            }
            return 0;
        default:
            return 0;
        }
    }

    @Override
    protected String getCharsetName() {
        return "GB2312";
    }

    /* (non-Javadoc)
     * @see com.m3958.encode.detector.AbstractDetector#getLanguageName()
     */
    @Override
    protected LanguageName getLanguageName() {
        return LanguageName.CHINESE;
    }
}
